package com.ksvip.next.components.groovy.autoconfigure;

import com.ksvip.next.components.groovy.compiler.DynamicCodeCompiler;
import com.ksvip.next.components.groovy.helper.ManualRegisterScriptHelper;
import com.ksvip.next.components.groovy.loader.EnhanceGroovyScriptRepository;
import com.ksvip.next.components.groovy.loader.RedisScriptLoader;
import com.ksvip.next.components.groovy.loader.ScriptLoader;
import com.ksvip.next.components.groovy.properties.GroovyRedisLoaderProperties;
import com.ksvip.next.components.groovy.registry.ScriptRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ksvip.next.components.groovy.annotation.condition.ConditionalOnExistingProperty;
import com.ksvip.next.components.groovy.properties.GroovyMysqlLoaderProperties;
import com.ksvip.next.components.groovy.helper.RegisterScriptToMysqlHelper;
import com.ksvip.next.components.groovy.loader.MysqlScriptLoader;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 自动配置类
 */
@Configuration
@EnableConfigurationProperties(value = { GroovyMysqlLoaderProperties.class })
@ConditionalOnExistingProperty(property = GroovyMysqlLoaderProperties.PREFIX + ".enable", value = "true")
public class GroovyMysqlLoaderAutoConfiguration {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 注入从MySQL里加载脚本的注册器
     */
    @Bean
    @ConditionalOnMissingBean(MysqlScriptLoader.class)
    public MysqlScriptLoader mysqlScriptLoader(DynamicCodeCompiler dynamicCodeCompiler,
                                               GroovyMysqlLoaderProperties groovyMysqlLoaderProperties,
                                               EnhanceGroovyScriptRepository enhanceGroovyScriptRepository) {
        this.logger.info("***loading ScriptLoader type is [{}]***", MysqlScriptLoader.class);
        return new MysqlScriptLoader(dynamicCodeCompiler, groovyMysqlLoaderProperties, enhanceGroovyScriptRepository);
    }

    @Bean
    @ConditionalOnMissingBean(RegisterScriptToMysqlHelper.class)
    public RegisterScriptToMysqlHelper registerScriptToMysqlHelper(EnhanceGroovyScriptRepository enhanceGroovyScriptRepository,
                                                                   ScriptLoader scriptLoader,
                                                                   ScriptRegistry scriptRegistry) {
        this.logger.info("***loading RegisterScriptToMysqlHelper ***", MysqlScriptLoader.class);

        return new RegisterScriptToMysqlHelper(enhanceGroovyScriptRepository, scriptLoader, scriptRegistry);
    }

}
